<script setup>
import { ref, defineEmits } from "vue"
import { searchMaterial } from "@/apis/search"
import ScanQrcodeComponent from "@/components/ScanQrCodeView.vue";
import defaultImg from "@/assets/material.png";

const keyWord = ref("")
const materialList = ref([])
const emit = defineEmits(['confirm'])
const current_page = ref(1)
const last_page = ref(1)
const total = ref(0)
const showScan = ref(false)

function loadData() {
  searchMaterial({
    condition: [
      ['name|material_id', 'like', "%" + keyWord.value + "%"]
    ]
  })
    .then(res => {
      const { code, data } = res.data;
      if (code === 1) {
        materialList.value = data.data;
        current_page.value = data.current_page;
        last_page.value = data.last_page;
        total.value = data.total
      }
    })
}

function onScroll(scrollBottom) {
  if (scrollBottom < 50) {
    current_page.value++
    loadData();
  }
}

function onConfirm(item) {
  item.total = 1;
  emit('confirm', item);
  materialList.value = [];
}

function scan(res) {
  keyWord.value = res;
  showScan.value = false;
}

</script>

<template>
  <div class="p-a">
    <t-search v-model="keyWord" placeholder="搜索" :onChange="loadData">
      <template #action>
        <t-icon @click="showScan=true" name="scan" style="margin-left: 8px;font-size: 20px;"></t-icon>
      </template>
    </t-search>
  </div>
  <div class="select-list" v-if="!showScan">
    <t-list @scroll="onScroll" v-if="total > 0">
      <t-cell v-for="item in materialList" :title="item.name" :key="item.id"
        :image="item.cover_info?.url != '' ? item.cover_info?.url : defaultImg" @click="onConfirm(item)">
        <template #description>
          <t-tag style="margin-right: 8px;">物品编码: {{ item.material_id }}</t-tag>
          <t-tag style="margin-right: 8px;" theme="success">物品规格: {{ item.specs }}</t-tag>
          <t-tag style="margin-right: 8px;margin-top: 8px;" theme="primary">库存数量: {{ item.total || 0 }}</t-tag>
        </template>
      </t-cell>
    </t-list>
    <t-cell v-else>暂无数据</t-cell>
  </div>
  <div class="scan-container" v-if="showScan">
    <ScanQrcodeComponent @onScan="scan"></ScanQrcodeComponent>
  </div>
</template>

<style scoped lang="less">
.p-a {
  padding: 12px;
  box-sizing: border-box;
}

.select-list {
  height: 300px;
  overflow: scroll;
}
</style>